package com.eduhzy.ttw.teacher.mvp.presenter;

import android.app.Application;
import android.content.Intent;
import android.os.Message;

import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.SPUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.eduhzy.ttw.commonres.utils.RxUtil;
import com.eduhzy.ttw.commonsdk.core.Constants;
import com.eduhzy.ttw.commonsdk.core.EventBusTags;
import com.eduhzy.ttw.commonsdk.core.RouterHub;
import com.eduhzy.ttw.commonsdk.entity.ChooseClassData;
import com.eduhzy.ttw.commonsdk.entity.ClassDetailsData;
import com.eduhzy.ttw.commonsdk.entity.CommonData;
import com.eduhzy.ttw.commonsdk.holder.AutoBaseViewHolder;
import com.eduhzy.ttw.teacher.mvp.contract.CreateClassContract;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.integration.AppManager;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.utils.RxLifecycleUtils;
import com.umeng.analytics.MobclickAgent;

import org.simple.eventbus.EventBus;

import java.net.ConnectException;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import me.jessyan.rxerrorhandler.handler.RetryWithDelay;


@ActivityScope
public class CreateClassPresenter extends BasePresenter<CreateClassContract.Model, CreateClassContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;
    @Inject
    BaseQuickAdapter<ChooseClassData, AutoBaseViewHolder> mAdapter;

    @Inject
    public CreateClassPresenter(CreateClassContract.Model model, CreateClassContract.View rootView) {
        super(model, rootView);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
    }

    public void getZxxx02ListByXxid() {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put(Constants.GROUPID, SPUtils.getInstance().getString(Constants.GROUPID));
        mModel.getZxxx02ListByXxid(map)
                .subscribeOn(Schedulers.io())
                .retryWhen(new RetryWithDelay(3, 2))//遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔
                .doOnSubscribe(disposable -> {
                    mRootView.showLoading();//显示下拉刷新的进度条
                }).subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doFinally(() -> {
                    mRootView.hideLoading();//隐藏下拉刷新的进度条
                })
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))//使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                .subscribe(new ErrorHandleSubscriber<CommonData<List<ChooseClassData>>>(mErrorHandler) {
                    @Override
                    public void onNext(CommonData<List<ChooseClassData>> commonData) {
                        if (!commonData.isResult() || ObjectUtils.isEmpty(commonData.getData())) {
                            mRootView.showMessage(commonData.getMessage());
                            mAdapter.setEmptyView(RxUtil.getEmptyView(mRootView.getActivity(), RxUtil.ErrorCode.no_data));
                        } else {
                            List<ChooseClassData> data = commonData.getData();
                            List<ChooseClassData> mLists = data;
                            mAdapter.getData().clear();
                            mAdapter.addData(mLists);
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        if (t instanceof ConnectException || t instanceof UnknownHostException) {
                            mAdapter.setEmptyView(RxUtil.getEmptyView(mRootView.getActivity(), RxUtil.ErrorCode.no_network));
                        } else {
                            mAdapter.setEmptyView(RxUtil.getEmptyView(mRootView.getActivity(), RxUtil.ErrorCode.load_error));
                        }
                    }
                });
    }

    public void saveClassAndReturnData(String name, String className, String code) {
        MobclickAgent.onEvent(mRootView.getActivity(), "ttw_create_class");
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("bjmc", name);
        map.put("njmc", className);
        map.put("nj", code);
        map.put("bzrgh", SPUtils.getInstance().getString(Constants.USERID));
        map.put("xxid", SPUtils.getInstance().getString(Constants.GROUPID));
        mModel.saveClassAndReturnData(map)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> {
                    mRootView.showLoading();//显示下拉刷新的进度条
                }).subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doFinally(() -> {
                    mRootView.hideLoading();//隐藏下拉刷新的进度条
                })
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))//使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                .subscribe(new ErrorHandleSubscriber<CommonData<ClassDetailsData>>(mErrorHandler) {
                    @Override
                    public void onNext(CommonData<ClassDetailsData> commonData) {
                        if (commonData.isResult()) {

                            Message obtain = Message.obtain();
                            obtain.what = EventBusTags.CREATE_CLASS_SUCCESS;
                            EventBus.getDefault().post(obtain, RouterHub.APP_MINECLASSACTIVITY);
                            ARouter.getInstance().build(RouterHub.APP_CREATECLASSSUCCESSACTIVITY)
                                    .withString(Intent.EXTRA_TITLE, Constants.CLASS_CREATE_SUCCESS)
                                    .withParcelable(Constants.ROUTER_DATA, commonData.getData())
                                    .navigation();
                            mRootView.killMyself();
                        } else {
                            mRootView.showMessage(commonData.getMessage());
                        }
                    }
                });

    }
}
